package com.erhairent.tools;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBHelp {

	private static String driver;
	private static String url;
	private static String user;
	private static String pwd;
	public Connection mconnection;
	private static DBHelp instance;

	public static DBHelp getInstance() {
		if (instance == null) {
			instance = new DBHelp();
		}
		return instance;
	}

	static {
		Properties pro = new Properties();
		InputStream is = DBHelp.class.getClassLoader().getResourceAsStream("config/db_config.properties");
		try {
			// 加载配置文件
			pro.load(is);
			// 读取配置文件
			driver = pro.getProperty("driver");
			url = pro.getProperty("url");
			user = pro.getProperty("user");
			pwd = pro.getProperty("pwd");

			System.out.println("配置文件读取成功");

		} catch (IOException e) {
			System.out.println("配置异常");
		}

	}

	// 与数据库连接
	public Connection getConnection() {
		if (mconnection == null) {
			try {
				// 加载驱动
				Class.forName(driver);

				mconnection = DriverManager.getConnection(url, user, pwd);

			} catch (ClassNotFoundException e) {
				System.out.println("加载数据失败");
			} catch (SQLException e) {
				System.out.println("打开连接失败");
			}
		}

		return mconnection;

	}

	public void closeConnection(Connection conn) {

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
